package cn.wolfcode.wolf2w.Interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserRedisService userRedisService;

    //登录前进行拦截请求
    //预处理回调方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 跨域请求是OPTIONS不带任何参数给拦截器拦住了,到不了跨域配置所以前端报跨域异常
         * 静态资源(页面)不拦截,动态资源属于HandlerMethod的实例才拦截
         * 解决拦截器跨域问题
         */
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod hi = (HandlerMethod) handler;
        //从请求头中获取token令牌
        String token = request.getHeader("token");
        //token令牌作为key获取对象
        UserInfo user = userRedisService.getUserByToken(token);
        //判断当前请求方法有无贴自定义注解
        //如果有贴注解就进行登录检查
        if (hi.hasMethodAnnotation(RequireLogin.class)){
            //判断是否有对象
            if(user == null){
                //转格式
                response.setContentType("application/json:charset=uft-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                //拦截
                return false;
            }
        }
        //如果没有贴注解就放行
        return true;

    }
}
